package com.cee.admin.common.utils;

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * http servlet 相关的工具类
 * 主要用于静态获取 request/response/session/sessionId
 *
 * @author rxliuli
 */
public final class HttpServletUtils {
    private HttpServletUtils() {
    }

    /**
     * 获取 request
     *
     * @return HttpServletRequest 对象
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }

    /**
     * 获取 response
     *
     * @return HttpServletResponse 对象
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
    }

    /**
     * 获取 session
     *
     * @return HttpSession 对象
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取会话标识 sessionId
     *
     * @return sessionId
     */
    public static String getSessionId() {
        return RequestContextHolder.currentRequestAttributes().getSessionId();
    }


    public static ServletOutputStream wrapDownloadResponse(String filename) throws IOException {
        HttpServletResponse httpServletResponse = null;
        try {
            httpServletResponse = getResponse();
            httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
            httpServletResponse.setContentType("application/octet-stream");
            httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException ignore) {
        }
        return httpServletResponse.getOutputStream();
    }

    /**
     * @param request 请求
     * @return ua
     */
    public static String getUserAgent(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");
        return ua != null ? ua : "";
    }

    public static String getClientIP(HttpServletRequest request) {
        return ServletUtil.getClientIP(request);
    }
}
